package com.financing.service.user;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.financing.components.payment.Gateway;
import com.financing.enums.invest.CouponRule;
import com.financing.model.Data;
import com.financing.model.system.Address;
import com.financing.model.user.Bank;
import com.financing.model.user.BankCard;
import com.financing.model.user.User;
import com.financing.service.BaseService;
import com.financing.service.invest.CouponService;
import com.financing.service.system.LoggerService;
import com.financing.util.DateUtil;
import com.financing.util.MD5Util;
import com.financing.util.Str;
import com.financing.util.XmlHelper;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class BankCardService extends BaseService<BankCard>{
	private static LoggerService log = new LoggerService();
	private static CouponService coupon = new CouponService();

	/**
	 * 绑卡主方法
	 * @param phone
	 * @param password
	 * @return
	 * @throws Exception 
	 */
	public synchronized static Ret bind(User u, Address city, Bank bank, String payPassword) throws Exception {
		// Gateway.设置实名信息
		String code = DateUtil.getTimeStamp();
		String payPass = MD5Util.encrypt(payPassword).toLowerCase();
		XmlHelper res = Gateway.post("/reg.action", 
			Data.put(
				"mchnt_txn_ssn",code, 
				"cust_nm",u.getRealName(),
				"certif_tp","0",
				"certif_id",u.getCertNum(),
				"mobile_no",u.getMobile(),
				"email","",
				"city_id",city.getCityId(),
				"parent_bank_id",bank.getCode(),
				"bank_nm","", 
				"capAcntNm","",
				"capAcntNo",u.getBankCard(), 
				"password",payPass,
				"lpassword","",
				"rem","",
				"sign","bank_nm,capAcntNm,capAcntNo,certif_id,city_id,cust_nm,email,lpassword,mchnt_cd,mchnt_txn_ssn,mobile_no,parent_bank_id,password,rem,ver"
			)
		);

		if(res.isSuccess() || res.getErrorMsg().contains("手机号重复")){
			u.setCode(u.getMobile())		//商户编码
				.setIsBindBankCard(1)
				.setBindCardTime(new Date())
				.update();
			
			new BankCard()
				.setCode(code)
				.setUserId(u.getId())
				.setBankName(bank.getName())
				.setBankCode(bank.getCode())
				.setAccountName(u.getRealName())
				.setBankAccount(u.getBankCard())
				.setMobile(u.getMobile())
				.setProvince(city.getProvince())
				.setCity(city.getCity())
				.setStatus("success")
				.setCreateTime(new Date())
				.save();
    		
			// 日志记录
			log.build("开户", "用户开户绑卡成功", u.getId(), "user");
			
			// 获取优惠券
			coupon.available(u.getId(), CouponRule.REAL);				
			
			// 刷新优惠券的姓名
			Db.update("update coupon_log set real_name=? where user_id=?",u.getRealName(),u.getId());
			
			return Ret.ok();
		}else {
			if(Str.eq("未找到卡bin[卡号错误]", res.getErrorMsg())) {
				return Ret.fail("msg", "银行卡卡号错误，请检查！");
			}else{
				return Ret.fail("msg", res.getErrorMsg());
			}
		}
	}
	
	/**
	 * 将用户其他银行卡设置为无效
	 * @param phone
	 * @param password
	 * @return
	 */
	public void setFailed(int userId) {
		Db.update("update bank_card set status='failed' where user_id=?",userId);
	}

	/**
	 * 返回用户启用的银行卡
	 * @param userid
	 * @return
	 */
	public BankCard findMainCard(int userId) {
		return BankCard.me.findFirst("select * from bank_card where user_id=? and status='success' ",userId); 
	}

	/**
	 * 根据编码查找银行卡
	 * @param unbind_card_id
	 * @return
	 */
	public BankCard findByCode(String code) {
		return BankCard.me.findFirst("select * from bank_card where code=?",code); 
	}

	/**
	 * 根据卡号查找银行卡
	 * @param unbind_card_id
	 * @return
	 */
	public BankCard findByAccount(String account) {
		return BankCard.me.findFirst("select * from bank_card where bank_account=?",account); 
	}
	
	/**
	 * 分页信息
	 * @param map 
	 * @return
	 */
	public Page<BankCard> list(int page, int size, Map<String, String> map) {
		return BankCard.me.paginate(page, size, buildSql("bank_card",Arrays.asList("user_id","status"),map));
	}
}
